package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.core.Result;
import com.dongdongshop.core.ResultEnum;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.ContentService;
import com.dongdongshop.service.UserService;
import com.dongdongshop.util.ShiroUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

@Controller
@RequestMapping("loginRegisterController")
public class LoginRegisterController {
    //开启日志
    Logger logger = LoggerFactory.getLogger(ContentController.class);
   @Resource
   private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Reference(check=false ,timeout=106666)
    private UserService userService;

    @RequestMapping("indexList")
    public String indexList(){
        return "/index";
    }

    @RequestMapping("registerList")
    public String registerList(){
        return "/register";
    }

    @RequestMapping("loginList")
    public String loginList(){
        return "/login";
    }

    @RequestMapping("getCode")
    @ResponseBody
    public Result getCode(String phone){
        try {
            logger.info("获取验证码方法开始运行{}");
            rocketMQTemplate.convertAndSend("cctv",phone);
        }catch (Exception e){
            Result.response(ResultEnum.ERROR);
            logger.error("出现错误，查看日志{}",e);
        }
        return Result.response(ResultEnum.SUCCESS);
    }

    @RequestMapping("register")
    @ResponseBody
    public Result register(TbUser user,String code){
        try {
            String salt = ShiroUtils.generateSalt(6);//获取盐，加密用的key
            String md5 = ShiroUtils.encryptPassword("MD5", user.getPassword(), salt, 10);
            user.setSalt(salt);
            user.setPassword(md5);

            String key = "codes";
            String feild =  user.getPhone();
            String code1 = (String)redisTemplate.boundHashOps(key).get(feild);
            if (code1 == null){
                return Result.response(ResultEnum.SUCCESS).setData("验证码过期");
            }else if(!code1.equals(code)){
                return Result.response(ResultEnum.SUCCESS).setData("验证码错误");
            }
            TbUser infoToLogin = userService.getInfoToLogin(user.getUsername());
            if (infoToLogin != null){
                return Result.response(ResultEnum.SUCCESS).setData("用户已存在");
            }
            logger.info("注册方法开始运行{}");
            user.setCreated(new Date());
            user.setUpdated(new Date());
            userService.register(user);
        }catch (Exception e){
            Result.response(ResultEnum.ERROR);
            logger.error("出现错误，查看日志{}",e);
        }
        return Result.response(ResultEnum.SUCCESS).setData("注册成功");
    }

    //登录
    @RequestMapping("userLogin")
    public String login(String username, String password, Model model){
        //使用shiro编写认证操作
        //1、获取subject
        Subject subject = SecurityUtils.getSubject();
        //2、封装用户信息
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //3、执行登录方法
        try {
            subject.login(token);
            //登录成功
            //获取用户session
            //TbUser user = (TbUser)subject.getPrincipal();
            model.addAttribute("msg",username);
            //redirect:/loginRegisterController/indexList
            return "redirect:/";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户不存在或者用户未认证");
            return "login";
        }catch (IncorrectCredentialsException e){
            //登录失败，密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
}
